"use client";

import { useRef, useState, useEffect, useContext } from "react";
import { 
  Box, 
  Flex, 
  Grid, 
  Text, 
  Button,
  useColorModeValue,
  useToast
} from "@chakra-ui/react";
import { KeyInfo } from "@/src/types/types";
import KBKeyboardView from "./KBKeyboardView";
import { MainContext } from "@/src/providers/MainProvider";
import MacroKeySetting from "./MacroKeySetting";
import _ from "lodash";

// 定义按键类型接口
interface KeycodeType {
  name: string;
  code: string;
  type: number;
  code1: number;
  code2: number;
  code3: number;
  langid?: string;
}

interface KeyCategoryType {
  id: string;
  langid: string;
  label: string;
  layout?: string;
  width?: string;
  keycodes: KeycodeType[];
}

function KBKeySetting() {
  const containerRef = useRef<HTMLDivElement>(null);
  const [keyboardHeight, setKeyboardHeight] = useState("40vh");
  const {
    connectedKeyboard,
    selectedKeyIndex,
    setSelectedKeyIndex,
    fnLayer,
    keyInfos,
    setKeyInfos,
    updateKeyboardKeys,
    kbMatrix,
    macroProfiles,
    t,
  } = useContext(MainContext);
  
  const toast = useToast();
  
  // 状态管理
  const [selectedCategory, setSelectedCategory] = useState('90'); // 默认选择Basic类别
  const [selectedKey, setSelectedKey] = useState<string | null>(null);
  const [keyCategories, setKeyCategories] = useState<KeyCategoryType[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  // 添加一个标记，用于跟踪数据是否已加载
  const dataLoadedRef = useRef(false);

  // 计算样式 - 与键盘风格保持一致
  const bgColor = useColorModeValue('rgba(255, 255, 255, 0.3)', 'rgba(30, 30, 35, 0.5)');
  const tabBgColor = useColorModeValue('rgba(255, 255, 255, 0.2)', 'rgba(0, 0, 0, 0.3)');
  const cardBgColor = useColorModeValue('rgba(255, 255, 255, 0.3)', 'rgba(40, 40, 40, 0.8)');
  const selectedCardBgColor = useColorModeValue('rgba(255, 165, 0, 0.2)', 'rgba(255, 165, 0, 0.2)');
  const selectedCardBorderColor = 'rgb(255, 140, 0)';
  const textColor = useColorModeValue('black', 'white');
  const selectedTextColor = 'rgb(255, 140, 0)';
  const keyBgColor = 'rgba(255, 255, 255, 0.3)';
  const keyTextColor = textColor;
  const keyBorderColor = 'rgba(255, 255, 255, 0.2)';
  const selectedTabBgColor = 'linear-gradient(135deg, rgb(255, 140, 0) 0%, rgb(255, 165, 0) 100%)';
  const subTextColor = useColorModeValue('gray.600', 'gray.400');
  const borderColor = useColorModeValue('rgba(255, 255, 255, 0.2)', 'rgba(255, 255, 255, 0.1)');
  
   // 加载按键数据
   useEffect(() => {
    const loadKeyData = async () => {
      try {
        // 如果数据已经加载过，则不再重复加载
        if (dataLoadedRef.current && keyCategories.length > 0) {
          return;
        }
        
        setIsLoading(true);
        
        // 动态导入JSON数据（兼容Electron环境）
        const customKeysData = await import('@/src/data/customkeys.json');
        const data = customKeysData.default || customKeysData;
        
        // 确保每个按键都有唯一的code属性，如果没有则创建一个
        const processedData = (data as any[]).map((category: any) => {
          return {
            ...category,
            keycodes: category.keycodes.map((key: any, index: number) => {
              // 如果key没有code属性，使用name+index创建一个唯一标识
              if (!key.code) {
                return { ...key, code: `${key.name}-${category.id}-${index}` };
              }
              return key;
            })
          };
        });
        
        setKeyCategories(processedData);
        dataLoadedRef.current = true;
        setIsLoading(false);
      } catch (error) {
        console.error("Error loading key data:", error);
        setIsLoading(false);
      }
    };
    
    loadKeyData();
  }, []);
  
  // 当类别切换时，清除选中的按键
  useEffect(() => {
    setSelectedKey(null);
  }, [selectedCategory]);

  // 根据窗口大小调整高度
  useEffect(() => {
    const updateHeight = () => {
      // 设置键盘高度为视窗高度的40%
      setKeyboardHeight("40vh");
    };
    
    updateHeight();
    window.addEventListener('resize', updateHeight);
    
    return () => {
      window.removeEventListener('resize', updateHeight);
    };
  }, []);

  // 键盘快捷键处理
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      // ESC键清除选中状态
      if (event.key === 'Escape') {
        setSelectedKeyIndex(-1);
        setSelectedKey(null);
        event.preventDefault();
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [setSelectedKeyIndex]);

  // 获取当前类别的按键
  const getCurrentKeys = () => {
    if (isLoading) return [];
    
    const category = keyCategories.find(cat => cat.id === selectedCategory);
    return category ? category.keycodes : [];
  };

  // 检查设备连接状态
  const checkDeviceConnection = () => {
    if (!connectedKeyboard) {
      toast({
        title: "设备未连接",
        description: "请先连接键盘设备",
        status: "error",
        duration: 3000,
        isClosable: true,
      });
      return false;
    }
    return true;
  };

  // 处理按键选择
  const handleKeySelect = async (keyInfo: KeycodeType) => {
    setSelectedKey(keyInfo.code);

    // 检查是否有选中的按键
    if (selectedKeyIndex === -1) {
      toast({
        title: "请先选择要设置的按键",
        status: "warning",
        duration: 2000,
        isClosable: true,
      });
      return;
    }
    
    try {
      // 深拷贝当前按键信息
      const newKeyInfos = _.cloneDeep(keyInfos);
      console.log("newKeyInfos", newKeyInfos, selectedKeyIndex);
      // 确保有足够的按键信息
      if (selectedKeyIndex >= newKeyInfos.length) {
        toast({
          title: "按键索引超出范围",
          status: "error",
          duration: 2000,
          isClosable: true,
        });
        return;
      }
      
      // 如果是Fn层，更新Fn按键信息
      if (fnLayer === 1) {
        newKeyInfos[selectedKeyIndex].fnName1 = keyInfo.name;
        newKeyInfos[selectedKeyIndex].fnType = keyInfo.type;
        newKeyInfos[selectedKeyIndex].fnCode1 = keyInfo.code1;
        newKeyInfos[selectedKeyIndex].fnCode2 = keyInfo.code2;
        newKeyInfos[selectedKeyIndex].fnCode3 = keyInfo.code3;
      } else {
        newKeyInfos[selectedKeyIndex].keyName = keyInfo.name;
        newKeyInfos[selectedKeyIndex].type = keyInfo.type;
        newKeyInfos[selectedKeyIndex].code1 = keyInfo.code1;
        newKeyInfos[selectedKeyIndex].code2 = keyInfo.code2;
        newKeyInfos[selectedKeyIndex].code3 = keyInfo.code3;
      }

      // 更新配置文件
      updateKeyboardKeys(newKeyInfos);
      
      // 更新当前显示的按键信息
      setKeyInfos(newKeyInfos);
      
      // 更新设备
      if (checkDeviceConnection()) {
        await connectedKeyboard!.setAllKeyInfo(newKeyInfos);
      }

      // 显示成功提示
      toast({
        title: "按键设置成功",
        description: `已将按键设置为 ${keyInfo.name}`,
        status: "success",
        duration: 2000,
        isClosable: true,
      });

      // 清除选中状态
      setSelectedKey(null);
      
    } catch (error) {
      console.error("设置按键失败:", error);
      toast({
        title: "设置按键失败",
        description: "请检查设备连接状态",
        status: "error",
        duration: 3000,
        isClosable: true,
      });
    }
  };

  // 获取按键类型对应的颜色
  const getKeyTypeColor = (type: number) => {
    switch(type) {
      case 16: // 鼠标
        return "rgba(255, 165, 0, 0.6)"; // 橙色
      case 31: // 自定义
        return "rgba(255, 140, 0, 0.6)"; // 橙色
      case 32: // 基本按键
        return "rgba(255, 120, 0, 0.6)"; // 深橙色
      case 48: // 多媒体
        return "rgba(255, 180, 0, 0.6)"; // 浅橙色
      case 64: // 电源类型
        return "rgba(255, 100, 0, 0.6)"; // 红橙色
      case 96: // 宏
        return "rgba(255, 200, 0, 0.6)"; // 金橙色
      default:
        return "rgba(255, 165, 0, 0.6)"; // 默认橙色
    }
  };

  // 按键类型是否要特殊显示
  const hasSpecialDisplay = (type: number) => {
    return type === 16 || type === 31 || type === 48 || type === 96;
  };

  // 处理拖动按键的逻辑
  const dragStart = (evt: any) => {
    const index = evt.target.dataset.index;
    const keyData = getCurrentKeys()[index];
    evt.dataTransfer.setData(
      "keyCode",
      JSON.stringify(keyData)
    );
    
    // 设置拖拽效果
    evt.dataTransfer.effectAllowed = "copy";
    
    // 添加视觉反馈
    evt.target.style.opacity = "0.5";
  };

  // 处理拖拽结束
  const dragEnd = (evt: any) => {
    // 恢复透明度
    evt.target.style.opacity = "1";
  };

  // 处理宏设置保存
  const handleMacroSave = async (macroIndex: number, macroType: number, loopCount?: number) => {
    if (selectedKeyIndex === -1) {
      toast({
        title: "请先选择要设置的按键",
        status: "warning",
        duration: 2000,
        isClosable: true,
      });
      return;
    }

    if (macroIndex >= macroProfiles.length) {
      toast({
        title: "宏索引超出范围",
        status: "error",
        duration: 2000,
        isClosable: true,
      });
      return;
    }
    
    try {
      // 深拷贝当前按键信息
      const newKeyInfos = _.cloneDeep(keyInfos);
      console.log("newKeyInfos", newKeyInfos, selectedKeyIndex);
      // 确保有足够的按键信息
      if (selectedKeyIndex >= newKeyInfos.length) {
        toast({
          title: "按键索引超出范围",
          status: "error",
          duration: 2000,
          isClosable: true,
        });
        return;
      }
      
      // 更新按键信息，保存宏设置
      const macroKeyInfo = {
        ...newKeyInfos[selectedKeyIndex],
      };

      // 如果是Fn层，更新Fn按键信息
      if (fnLayer === 1) {
        macroKeyInfo.fnName1 = macroProfiles[macroIndex].name;
        macroKeyInfo.fnType = 0x70;
        macroKeyInfo.fnCode1 = macroIndex;
        macroKeyInfo.fnCode2 = loopCount || 0;
        macroKeyInfo.fnCode3 = macroType;
      } else {
        macroKeyInfo.keyName = macroProfiles[macroIndex].name;
        macroKeyInfo.type = 0x70;
        macroKeyInfo.code1 = macroIndex;
        macroKeyInfo.code2 = loopCount || 0;
        macroKeyInfo.code3 = macroType;
      }

      newKeyInfos[selectedKeyIndex] = macroKeyInfo;

      // 更新配置文件
      updateKeyboardKeys(newKeyInfos);
      
      // 更新当前显示的按键信息
      setKeyInfos(newKeyInfos);
      
      // 更新设备
      if (checkDeviceConnection()) {
        await connectedKeyboard!.setAllKeyInfo(newKeyInfos);
      }

    } catch (error) {
      console.error("设置宏失败:", error);
      toast({
        title: "设置宏失败",
        description: "请检查设备连接状态和宏配置",
        status: "error",
        duration: 3000,
        isClosable: true,
      });
    }
  };

  return (
    <Box 
      ref={containerRef} 
      className="w-full h-full flex flex-col"
      style={{
        marginLeft: "25px",
        width: "calc(100% - 50px)"
      }}
    >
      {/* 键盘预览区域 */}
      <Box 
        style={{ 
          height: keyboardHeight,
          padding: "10px",
          display: "flex",
          alignItems: "center",
          justifyContent: "center"
        }}
      >
        <KBKeyboardView />
      </Box>
      
      {/* 底部编辑区域 */}
      <Box 
        p={6} 
        style={{ 
          flex: 1,
          background: 'rgba(255, 255, 255, 0.8)',
          backdropFilter: 'blur(20px)',
          WebkitBackdropFilter: 'blur(20px)',
          border: '1px solid rgba(255, 165, 0, 0.2)',
          borderRadius: '16px',
          boxShadow: '0 8px 32px rgba(255, 165, 0, 0.1)',
          margin: "0 10px 10px 10px",
          overflow: "hidden",
        }}
      >
        {/* 居中显示按键设置区域 */}
        <Flex direction="column" height="100%" maxWidth="800px" mx="auto">
          {/* 上方按键分类选择 */}
          <Box 
            bg={tabBgColor}
            borderRadius="12px"
            mb={5}
            width="100%"
            backdropFilter="blur(8px)"
            border="1px solid rgba(255, 255, 255, 0.1)"
          >
            <Flex 
              justify="center" 
              align="center"
              height="42px"
              px={2}
              maxW="100%"
              overflowX="auto"
              css={{
                '&::-webkit-scrollbar': {
                  height: '4px',
                },
                '&::-webkit-scrollbar-track': {
                  background: 'rgba(255, 255, 255, 0.1)',
                  borderRadius: '4px',
                },
                '&::-webkit-scrollbar-thumb': {
                  background: 'rgba(255, 165, 0, 0.3)',
                  borderRadius: '4px',
                },
              }}
            >
              {!isLoading && keyCategories.map((category) => (
                <Box
                  key={category.id}
                  bg={selectedCategory === category.id ? selectedTabBgColor : 'transparent'}
                  color={selectedCategory === category.id ? 'white' : 'rgb(71, 85, 105)'}
                  onClick={() => setSelectedCategory(category.id)}
                  cursor="pointer"
                  borderRadius="8px"
                  fontWeight={selectedCategory === category.id ? "bold" : "normal"}
                  fontSize="sm"
                  height="30px"
                  px={4}
                  mx={0.5}
                  minW="90px"
                  display="flex"
                  alignItems="center"
                  justifyContent="center"
                  transition="all 0.2s"
                  style={{
                    background: selectedCategory === category.id ? selectedTabBgColor : 'transparent',
                  }}
                  _hover={{ 
                    bg: selectedCategory === category.id ? '' : 'rgba(255, 165, 0, 0.1)',
                    color: selectedCategory === category.id ? 'white' : 'rgb(255, 140, 0)'
                  }}
                >
                  {t(category.langid)}
                </Box>
              ))}
            </Flex>
          </Box>
          
          {/* 下方内容区域 */}
          {selectedCategory === '96' ? (
            // 宏设置界面
            <MacroKeySetting
              selectedKeyIndex={selectedKeyIndex}
              fnLayer={fnLayer}
              onSave={handleMacroSave}
            />
          ) : (
            // 其他按键设置界面
            <Box 
              flex="1"
              overflowY="auto"
              css={{
                '&::-webkit-scrollbar': {
                  width: '6px',
                },
                '&::-webkit-scrollbar-track': {
                  background: 'rgba(255, 165, 0, 0.1)',
                  borderRadius: '8px',
                },
                '&::-webkit-scrollbar-thumb': {
                  background: 'rgba(255, 165, 0, 0.3)',
                  borderRadius: '8px',
                },
              }}
            >
              {isLoading ? (
                <Text textAlign="center" color={textColor}>Loading...</Text>
              ) : (
                <Grid 
                  templateColumns="repeat(auto-fill, minmax(140px, 140px))"
                  gap="12px"
                  py={4}
                  px={2}
                  justifyContent="center"
                >
                  {getCurrentKeys().map((key, index) => (
                    <Box
                      key={key.code}
                      height="52px"
                      width="140px"
                      px={3}
                      py={2}
                      textAlign="center"
                      borderRadius="16px"
                      cursor="pointer"
                      bg="rgba(255, 255, 255, 0.4)"
                      border="1px solid"
                      borderColor={selectedKey === key.code ? 'rgba(255, 140, 0, 0.6)' : 'rgba(255, 255, 255, 0.3)'}
                      onClick={() => handleKeySelect(key)}
                      data-index={index}
                      draggable
                      onDragStart={dragStart}
                      onDragEnd={dragEnd}
                      transition="all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"
                      position="relative"
                      overflow="hidden"
                      backdropFilter="blur(12px)"
                      style={{
                        background: selectedKey === key.code 
                          ? 'linear-gradient(135deg, rgba(255, 140, 0, 0.15) 0%, rgba(255, 165, 0, 0.15) 50%, rgba(255, 180, 0, 0.1) 100%)'
                          : 'linear-gradient(135deg, rgba(255, 255, 255, 0.4) 0%, rgba(255, 255, 255, 0.2) 50%, rgba(255, 255, 255, 0.1) 100%)',
                        boxShadow: selectedKey === key.code
                          ? '0 8px 32px rgba(255, 165, 0, 0.2), 0 2px 8px rgba(255, 140, 0, 0.1), inset 0 1px 0 rgba(255, 255, 255, 0.3)'
                          : '0 4px 16px rgba(0, 0, 0, 0.08), 0 1px 4px rgba(0, 0, 0, 0.04), inset 0 1px 0 rgba(255, 255, 255, 0.3)',
                        WebkitBackdropFilter: 'blur(12px)',
                        transform: selectedKey === key.code ? 'translateY(-2px) scale(1.02)' : 'translateY(0) scale(1)',
                      }}
                      _hover={{ 
                        borderColor: selectedKey === key.code ? 'rgba(255, 140, 0, 0.8)' : 'rgba(255, 165, 0, 0.4)',
                        transform: selectedKey === key.code ? 'translateY(-2px) scale(1.02)' : 'translateY(-1px) scale(1.01)',
                        boxShadow: selectedKey === key.code
                          ? '0 12px 40px rgba(255, 165, 0, 0.25), 0 4px 12px rgba(255, 140, 0, 0.15), inset 0 1px 0 rgba(255, 255, 255, 0.4)'
                          : '0 8px 24px rgba(255, 165, 0, 0.12), 0 2px 8px rgba(255, 140, 0, 0.08), inset 0 1px 0 rgba(255, 255, 255, 0.4)',
                        background: selectedKey === key.code 
                          ? 'linear-gradient(135deg, rgba(255, 140, 0, 0.2) 0%, rgba(255, 165, 0, 0.2) 50%, rgba(255, 180, 0, 0.15) 100%)'
                          : 'linear-gradient(135deg, rgba(255, 165, 0, 0.08) 0%, rgba(255, 255, 255, 0.3) 50%, rgba(255, 255, 255, 0.2) 100%)'
                      }}
                      _active={{
                        transform: selectedKey === key.code ? 'translateY(-1px) scale(1.01)' : 'translateY(0) scale(0.99)',
                      }}
                      display="flex"
                      flexDirection="column"
                      alignItems="center"
                      justifyContent="center"
                      gap={1}
                    >
                      {/* 顶部装饰线 */}
                      {hasSpecialDisplay(key.type) && (
                        <Box
                          position="absolute"
                          top={0}
                          left={0}
                          right={0}
                          height="3px"
                          borderRadius="16px 16px 0 0"
                          style={{
                            background: `linear-gradient(90deg, ${getKeyTypeColor(key.type)}, ${getKeyTypeColor(key.type).replace('0.6', '0.8')}, ${getKeyTypeColor(key.type)})`
                          }}
                        />
                      )}
                      
                      {/* 光泽效果 */}
                      <Box
                        position="absolute"
                        top="2px"
                        left="3px"
                        right="3px"
                        height="20px"
                        borderRadius="12px"
                        background="linear-gradient(180deg, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0.1) 50%, transparent 100%)"
                        pointerEvents="none"
                      />
                      
                      {/* 主要文字 */}
                      <Text 
                        color={selectedKey === key.code ? 'rgb(255, 140, 0)' : 'rgb(71, 85, 105)'} 
                        fontSize="14px"
                        fontWeight={selectedKey === key.code ? "600" : "500"}
                        maxWidth="130px"
                        lineHeight="1.2"
                        isTruncated={true}
                        title={key.langid ? t(key.langid) : key.name}
                        style={{
                          textShadow: selectedKey === key.code 
                            ? '0 1px 2px rgba(255, 140, 0, 0.3)' 
                            : '0 1px 2px rgba(255, 255, 255, 0.8)'
                        }}
                      >
                        {key.type == 2 ? t(key.langid) + " " + (index + 1) : key.langid ? t(key.langid) : key.name}
                      </Text>
                    </Box>
                  ))}
                </Grid>
              )}
            </Box>
          )}
        </Flex>
      </Box>
    </Box>
  );
}

export default KBKeySetting;
